<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <p >
        省：<select name="" id="sel1">
            <option value="">请选择</option>
        </select>
        市：<select name="" id="sel2"></select>
        区：<select name="" id="sel3"></select>
    </p>
    你选的地址为：<h1 id="address"></h1>
    <script src="../js/address.js"></script>
    <script>
        var sel1 = document.getElementById("sel1")
        var sel2 = document.getElementById("sel2")
        var sel3 = document.getElementById("sel3")
        var address = document.getElementById("address")
        var cityArr = []; //市级数组
        var areaArr = []; //区级数组
 
        //省级遍历
        citys.forEach(v => {
            var option = new Option(v.name);
            sel1.options.add(option);//省
        })
 
        var sel1Index = 0;
        sel1.onchange = function () {
            // console.log(this.selectedIndex);//请选择和省级下标 (这里的请选择下标为0，省级下标从1开始)
 
            sel1Index = this.selectedIndex - 1;// 设定数组省级下标从0开始
            //  console.log(sel1Index);
            sel2.options.length = 0;//点击省选项改变清空之前市级选项
            sel3.options.length = 0;
            if (sel1Index != -1) {
                cityArr = citys[sel1Index].city
                //console.log(cityArr);
                //市级遍历
                cityArr.forEach(v => {
                    var option = new Option(v.name);
                    sel2.options.add(option);//市
                })
 
                areaArr = cityArr[0].area;
                sel3.options.length = 0; 
                //区级遍历
                areaArr.forEach(v => {
                    var option = new Option(v);
                    sel3.options.add(option);//区
                })
 
                 address.innerText = citys[sel1Index].name + cityArr[0].name + areaArr[0];
            }
            else{
                address.innerText = ""; 
            }
        }
 
        var sel2Index = 0;
        sel2.onchange = function(){
            sel2Index = this.selectedIndex;
            console.log(sel2Index);
            areaArr = cityArr[sel2Index].area;
          
            sel3.options.length = 0;
            //区级遍历
            areaArr.forEach(v => {
                    var option = new Option(v);
                    sel3.options.add(option);//区
                }) 
                address.innerText = citys[sel1Index].name + cityArr[sel2Index].name + areaArr[0];  
        }
        var sel3Index = 0;
        sel3.onchange = function(){
            sel3Index = this.selectedIndex;
            address.innerText = citys[sel1Index].name + cityArr[sel2Index].name + areaArr[sel3Index];  
 
        }
 
    </script>
</body>
</html>